/**
 * 
 */
package mdb.com.vn.web.beans;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.xml.rpc.ServiceException;

import mdb.com.vn.model.Casa;
import mdb.com.vn.model.FixedDepositCasa;
import mdb.com.vn.model.FixedDeposits;
import mdb.com.vn.model.LuckyDraw;
import mdb.com.vn.model.ScratchCard;
import mdb.com.vn.services.MDBServices;
import mdb.com.vn.utils.DateUtils;
import mdb.com.vn.utils.NumberUtils;
import mdb.com.vn.web.utils.FacesContextUtils;
import mdb.com.vn.wservices.utils.FDCasaFromT24;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 * @author tu.dod
 * 
 */
@ManagedBean(name = "processFDCSBeans")
@ViewScoped
public class ProcessFDCSBeans implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String savingBookNo;
	private String savingAccountNo;
	private int number00k;
	private int number20k;
	private int number50k;
	private int number100k;
	private int number200k;
	private int number500k;

	private String detail20k;
	private String detail50k;
	private String detail100k;
	private String detail200k;
	private String detail500k;

	private FixedDepositCasa fixedDepositCasa;
	private StreamedContent file;

	private boolean btnVisible;
	private boolean btnSaveVisible;
	private boolean componentVisible;
	private int totalScradAvailable;

	@ManagedProperty("#{mdbServices}")
	private MDBServices mdbServices;

	@PostConstruct
	public void init() {
		savingBookNo = "";
		savingAccountNo = "";
		fixedDepositCasa = new FixedDepositCasa();
	}

	public void searchFDCASAfromT24P() throws Exception {
		try {
			fixedDepositCasa = new FixedDepositCasa();
			if (savingBookNo.equals("") || savingAccountNo.equals("")) {
				FacesContext
						.getCurrentInstance()
						.addMessage(
								null,
								new FacesMessage(
										FacesMessage.SEVERITY_WARN,
										"Nhập số sổ tiết kiệm và tài khoản tiết kiệm không kì hạn là thông tin bắt buộc!",
										"Vui lòng nhập lại"));
			} else {
				if (savingBookNo.substring(0, 1).equals("6")
						&& savingBookNo.length() == 11
						&& savingAccountNo.substring(0, 1).equals("2")
						&& savingAccountNo.length() == 11) {
					FixedDepositCasa depositsCasa = mdbServices
							.findFixedDepositCasaByCode(savingBookNo,
									savingAccountNo);
					FixedDeposits deposits = mdbServices
							.findFixedDepositsByCode(savingBookNo);
					Casa casa = mdbServices.findCasaByCode(savingAccountNo);
					if (depositsCasa != null || deposits != null
							|| casa != null) {
						fixedDepositCasa.setLuckyDraw(0);
						fixedDepositCasa.setScCard(0);
						setBtnSaveVisible(false);
						FacesContext
								.getCurrentInstance()
								.addMessage(
										null,
										new FacesMessage(
												FacesMessage.SEVERITY_WARN,
												"Tài khoản này đã tham chương trình khuyến mãi rồi ",
												"Vui lòng xem lại thể lệ chương trình"));
					} else {
						fixedDepositCasa = FDCasaFromT24
								.getFDCASAInfoFromT24(fixedDepositCasa,
										savingBookNo, savingAccountNo);
						Date startDateFD = fixedDepositCasa.getStartDate();
						Date startDateCS = fixedDepositCasa.getOpeningDate();
						Date promotion = DateUtils
								.createDateYYYYMMDD("20131209");
						if (fixedDepositCasa.getLuckyDraw() == 0
								|| startDateFD.compareTo(promotion) < 0
								|| startDateCS.compareTo(promotion) < 0) {

							setBtnSaveVisible(false);
							FacesContext
									.getCurrentInstance()
									.addMessage(
											null,
											new FacesMessage(
													FacesMessage.SEVERITY_WARN,
													"Tài khoản không tồn tại hoặc không đủ điều kiện tham gia chương trình khuyến mãi! ",
													"Vui lòng kiểm tra lại hoặc xem thể lệ chương trình"));
						} else {
							if (fixedDepositCasa.getCustomerType() == 1) {
								setTotalScradAvailable(mdbServices
										.getSCardFDAvailable(fixedDepositCasa
												.getCustomerId())
										+ mdbServices
												.getSCardCSAvailable(fixedDepositCasa
														.getCustomerId())
										+ mdbServices
												.getSCardFDCSAvailable(fixedDepositCasa
														.getCustomerId()));
								int tocalculatebag = fixedDepositCasa
										.getScCard() + getTotalScradAvailable();
								fixedDepositCasa.setBagGift(tocalculatebag / 5);
								fixedDepositCasa
										.setTrayGift(tocalculatebag / 10);
							}
							setBtnSaveVisible(true);
						}
					}

				} else {
					setBtnSaveVisible(false);
					FacesContext
							.getCurrentInstance()
							.addMessage(
									null,
									new FacesMessage(
											FacesMessage.SEVERITY_WARN,
											"Không đúng định dạng của số Sổ tiết kiệm và số Tài khoản tiết kiệm ",
											"Vui lòng nhập lại 11 chữ số và chữ số đầu tiên của Sổ tiết kiệm là 6, Tài khoản tiết kiệm là 2"));
				}
			}

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		}

	}

	public void addNewFixedDepositCasaP() {
		int total_sc = number00k + number20k + number50k + number100k + number200k
				+ number500k;
		int total_sc_full = fixedDepositCasa.getScCard()
				+ getTotalScradAvailable();
		int bagReceived = fixedDepositCasa.getBgiftReceived();
		int trayReceived = fixedDepositCasa.getTgiftReceived();

		bagReceived = bagReceived * 5;
		trayReceived = trayReceived * 10;
		int total_sc_received = bagReceived + trayReceived;

		if (total_sc > fixedDepositCasa.getScCard()
				|| total_sc_received > total_sc_full) {
			setBtnSaveVisible(true);
			FacesContext
					.getCurrentInstance()
					.addMessage(
							null,
							new FacesMessage(
									FacesMessage.SEVERITY_WARN,
									"Vượt quá số lượng áo thun, khay mứt và thẻ cào cho phép ",
									"Vui lòng nhập lại"));
		} else {

			if (total_sc == fixedDepositCasa.getScCard()) {
				try {
					fixedDepositCasa.setScCardNotGet(fixedDepositCasa
							.getScCard() - total_sc_received);
					mdbServices.addFixedDepositCasa(fixedDepositCasa);

					for (int i = 0; i < fixedDepositCasa.getLuckyDraw(); i++) {
						LuckyDraw luckyDraw = new LuckyDraw();
						luckyDraw.setCustomerRef(fixedDepositCasa
								.getCustomerId());
						luckyDraw.setTransRef(fixedDepositCasa
								.getSavingbookNo());
						luckyDraw.setTransRef1(fixedDepositCasa
								.getAccountLocked());
						luckyDraw
								.setLdrDesription("Số dự thưởng cho "
										+ fixedDepositCasa.getCustomerName());
						luckyDraw.setStatus(1);
						luckyDraw.setCreatedBy(fixedDepositCasa.getCreatedBy());
						luckyDraw.setDateCreated(new Date());
						mdbServices.addLuckyDraw(luckyDraw);
					}
					if (number20k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(fixedDepositCasa
								.getSavingbookNo());
						scratchCard.setTransRef1(fixedDepositCasa
								.getAccountLocked());
						scratchCard.setCreatedBy(fixedDepositCasa
								.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail20k);
						scratchCard.setCustomerRef(fixedDepositCasa
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(20000);
						scratchCard.setQuantity(number20k);
						mdbServices.addScratchCard(scratchCard);
					}
					if (number50k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(fixedDepositCasa
								.getSavingbookNo());
						scratchCard.setTransRef1(fixedDepositCasa
								.getAccountLocked());
						scratchCard.setCreatedBy(fixedDepositCasa
								.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail50k);
						scratchCard.setCustomerRef(fixedDepositCasa
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(50000);
						scratchCard.setQuantity(number50k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number100k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(fixedDepositCasa
								.getSavingbookNo());
						scratchCard.setTransRef1(fixedDepositCasa
								.getAccountLocked());
						scratchCard.setCreatedBy(fixedDepositCasa
								.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail100k);
						scratchCard.setCustomerRef(fixedDepositCasa
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(100000);
						scratchCard.setQuantity(number100k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number200k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(fixedDepositCasa
								.getSavingbookNo());
						scratchCard.setTransRef1(fixedDepositCasa
								.getAccountLocked());
						scratchCard.setCreatedBy(fixedDepositCasa
								.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail200k);
						scratchCard.setCustomerRef(fixedDepositCasa
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(200000);
						scratchCard.setQuantity(number200k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number500k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(fixedDepositCasa
								.getSavingbookNo());
						scratchCard.setTransRef1(fixedDepositCasa
								.getAccountLocked());
						scratchCard.setCreatedBy(fixedDepositCasa
								.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail500k);
						scratchCard.setCustomerRef(fixedDepositCasa
								.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(500000);
						scratchCard.setQuantity(number500k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number00k > 0){
						fixedDepositCasa.setCheckGetThankSC(number00k);
					}
					// /////////////////////////
					String fileName = fixedDepositCasa.getSavingbookNo() + "-"
							+ fixedDepositCasa.getAccountLocked() + ".pdf";
					Map<String, Object> data = new HashMap<String, Object>();

					data.put("BranchID", fixedDepositCasa.getBranchCode());
					data.put("CustomerID", fixedDepositCasa.getCustomerId());
					data.put("CustomerName", fixedDepositCasa.getCustomerName());
					data.put("SavingBookNo", fixedDepositCasa.getSavingbookNo());
					data.put("FDAmount", NumberUtils.format(fixedDepositCasa
							.getFdAmount().toString(), "###,###,###,###"));
					data.put("FDTerm", fixedDepositCasa.getFdTerm());
					data.put("FDInterest",
							Double.toString(fixedDepositCasa.getInterestRate()));
					data.put("SavingAccountNo",
							fixedDepositCasa.getAccountLocked());
					data.put("CSAmount", NumberUtils.format(fixedDepositCasa
							.getWbBalances().toString(), "###,###,###,###"));
					data.put("TotalSCard", fixedDepositCasa.getScCard());
					data.put("TotalLDR", fixedDepositCasa.getLuckyDraw() / 2);

					data.put("BranchName", mdbServices
							.getCompanyNameByCode(fixedDepositCasa
									.getBranchCode()));
					data.put(
							"LuckyDrawCodes",
							mdbServices.getAllLuckyDrawCodeP(
									fixedDepositCasa.getSavingbookNo(), 0));
					data.put("DateExpired",DateUtils.format(fixedDepositCasa.getEndDateLocked(), "dd/MM/yyyy") );
					List<ScratchCard> scratchCards = mdbServices
							.getScratchCardByRef(fixedDepositCasa
									.getSavingbookNo());
					double totalSCAmount = 0;
					for (ScratchCard scratchCard : scratchCards) {
						if (scratchCard.getScDenomination() == 20000) {
							data.put("Card20k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 20000;
						}
						if (scratchCard.getScDenomination() == 50000) {
							data.put("Card50k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 50000;
						}
						if (scratchCard.getScDenomination() == 100000) {
							data.put("Card100k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 100000;
						}
						if (scratchCard.getScDenomination() == 200000) {
							data.put("Card200k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 200000;
						}
						if (scratchCard.getScDenomination() == 500000) {
							data.put("Card500k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 500000;
						}
					}
					data.put("TotalSCAmount", NumberUtils.format(totalSCAmount,
							"###,###,###,###"));
					data.put(
							"ImagesPath",
							FacesContextUtils
									.getResourcePath("/WEB-INF/classes/mdb/com/vn/web/reports/MDB.jpg"));

					FixedDepositCasa depositsCasa = mdbServices
							.findFixedDepositCasaByCode(
									fixedDepositCasa.getSavingbookNo(),
									fixedDepositCasa.getAccountLocked());

					if (fixedDepositCasa.getCustomerType() == 1) {
						// update FD to DB
						fixedDepositCasa.setId(depositsCasa.getId());
							data.put("ThanksCard", fixedDepositCasa.getCheckGetThankSC());
						data.put("TshirtGift",
								fixedDepositCasa.getBgiftReceived());
						data.put("TrayGift",
								fixedDepositCasa.getTgiftReceived());
						fixedDepositCasa.setScCardAmt(totalSCAmount);

						mdbServices.updateFixedDepositCasa(fixedDepositCasa);

						JasperReport jasperReport = JasperCompileManager
								.compileReport(FacesContextUtils
										.getResourcePath("/WEB-INF/classes/mdb/com/vn/web/reports/FDCASAReport.jrxml"));

						JasperPrint jasperPrint = JasperFillManager.fillReport(
								jasperReport, data, new JREmptyDataSource());

						JasperExportManager.exportReportToPdfFile(jasperPrint,
								fileName);
					}

					File filetemps = new File(fileName);
					InputStream fis = new FileInputStream(filetemps);
					file = new DefaultStreamedContent(fis, "application/pdf",
							fileName);
					filetemps = new File(filetemps.getCanonicalPath());
					filetemps.delete();
					setBtnVisible(true);
					setBtnSaveVisible(false);
					FacesContext.getCurrentInstance().addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_INFO,
									"Lưu thông tin thành công",
									"Bấm nút 'In phiếu thông tin' để in phiếu thông tin cho khách hàng"));

				} catch (Exception e) {
					setBtnSaveVisible(true);
					FacesContext.getCurrentInstance().addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_ERROR,
									"Lỗi xảy ra trong qua trình nhập liệu",
									"Vui lòng kiểm tra lại"));
					e.printStackTrace();
				}
			} else {
				setBtnSaveVisible(true);
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_WARN,
								"Nhập chưa đầy đủ số lượng thẻ cào",
								"Vui lòng kiểm tra lại"));
			}

		}
	}

	public void downloadPrevented() {
		setBtnVisible(true);
		file = null;
	}

	public String getSavingBookNo() {
		return savingBookNo;
	}

	public void setSavingBookNo(String savingBookNo) {
		this.savingBookNo = savingBookNo;
	}

	public String getSavingAccountNo() {
		return savingAccountNo;
	}

	public void setSavingAccountNo(String savingAccountNo) {
		this.savingAccountNo = savingAccountNo;
	}

	public int getNumber20k() {
		return number20k;
	}

	public void setNumber20k(int number20k) {
		this.number20k = number20k;
	}

	public int getNumber50k() {
		return number50k;
	}

	public void setNumber50k(int number50k) {
		this.number50k = number50k;
	}

	public int getNumber100k() {
		return number100k;
	}

	public void setNumber100k(int number100k) {
		this.number100k = number100k;
	}

	public int getNumber200k() {
		return number200k;
	}

	public void setNumber200k(int number200k) {
		this.number200k = number200k;
	}

	public int getNumber500k() {
		return number500k;
	}

	public void setNumber500k(int number500k) {
		this.number500k = number500k;
	}

	public String getDetail20k() {
		return detail20k;
	}

	public void setDetail20k(String detail20k) {
		this.detail20k = detail20k;
	}

	public String getDetail50k() {
		return detail50k;
	}

	public void setDetail50k(String detail50k) {
		this.detail50k = detail50k;
	}

	public String getDetail100k() {
		return detail100k;
	}

	public void setDetail100k(String detail100k) {
		this.detail100k = detail100k;
	}

	public String getDetail200k() {
		return detail200k;
	}

	public void setDetail200k(String detail200k) {
		this.detail200k = detail200k;
	}

	public String getDetail500k() {
		return detail500k;
	}

	public void setDetail500k(String detail500k) {
		this.detail500k = detail500k;
	}

	public FixedDepositCasa getFixedDepositCasa() {
		return fixedDepositCasa;
	}

	public void setFixedDepositCasa(FixedDepositCasa fixedDepositCasa) {
		this.fixedDepositCasa = fixedDepositCasa;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public boolean isBtnVisible() {
		return btnVisible;
	}

	public void setBtnVisible(boolean btnVisible) {
		this.btnVisible = btnVisible;
	}

	public boolean isBtnSaveVisible() {
		return btnSaveVisible;
	}

	public void setBtnSaveVisible(boolean btnSaveVisible) {
		this.btnSaveVisible = btnSaveVisible;
	}

	public void setMdbServices(MDBServices mdbServices) {
		this.mdbServices = mdbServices;
	}

	public boolean isComponentVisible() {
		return componentVisible;
	}

	public void setComponentVisible(boolean componentVisible) {
		this.componentVisible = componentVisible;
	}

	public int getTotalScradAvailable() {
		return totalScradAvailable;
	}

	public void setTotalScradAvailable(int totalScradAvailable) {
		this.totalScradAvailable = totalScradAvailable;
	}

	public int getNumber00k() {
		return number00k;
	}

	public void setNumber00k(int number00k) {
		this.number00k = number00k;
	}

}
